package com.zhugang.week13.recursion;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program algorithms
 * @description: reversePrint2
 * @author: chanzhugang
 * @create: 2022/11/17 11:19
 */
public class ReversePrint2 {

    /**
     * 剑指offer 06 从尾到头打印链表
     * https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
     *
     * @param head
     * @return
     */
    List<Integer> list = new ArrayList<>();

    public int[] reversePrint(ListNode head) {
        /**
         * 递归实现，深度优先搜索
         */
        reverse(head);
        /*int[] arr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            arr[i] = list.get(i);
        }*/
        int[] arr = list.stream().mapToInt(integer -> integer).toArray();
        return arr;
    }

    private void reverse(ListNode head) {
        if (head == null) {
            return;
        }
        reverse(head.next);
        list.add(head.val);
    }

    public int[] reversePrint2(ListNode head) {
        /**
         * 栈也适合，后进先出
         */
        Stack<Integer> stack = new Stack<>();
        ListNode p = head;
        while (p != null) {
            stack.push(p.val);
            p = p.next;
        }
        int[] arr = new int[stack.size()];
        int i = 0;
        while (!stack.isEmpty()) {
            arr[i] = stack.pop();
            i++;
        }
        return arr;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}